<?php
namespace app\admin\controller;
use think\Controller;
use app\admin\model\Role;
use think\Validate;
use think\Db;
use app\admin\model\Node;
use app\admin\controller\Main;
class Roles extends Main
{
    public function roleList()
    {
        $name = input('post.name');
        if(empty($name)){
            $data = Role::where(true)->paginate(4);
        }else{
             $data = Role::where('role_name','like',"%$name%")->paginate(4);
        }
    	
    	$count = Role::count();
    	$this->assign('count',$count);
    	$this->assign('list',$data);
        return $this->fetch('admin/admin-role');
    }

    public function addRole()
    {
        $res = Node::all();
        $this->assign('list',$res);
    	return $this->fetch('role/role-add');
    }

    //添加角色
    public function add()
    {
    	$data = input('post.');
    	$ids = $data['id'];
    	$validate = new Validate([
			    'role_name'  => 'require|min:1',
			    'role_power' => 'max:20'
		]);
		if (!$validate->check($data)) {
		    $arr = ['status'=>'0','content'=>$validate->getError()];
		} else {
    		$role['role_name'] = $data['role_name'];
    		$role['role_power'] = $data['role_power'];
    		$role['role_addtime'] = time();
    		$role['role_status'] = 1;
    		$row = Role::create($role);
    		if($row->role_id){
    			$arr = ['status'=>'1','content'=>'添加成功'];
    			foreach($ids as $v){
    				Db::name('role_node')->insert(['rid'=>$row->role_id,'nid'=>$v]);
    			}
    		}else{
    			$arr = ['status'=>'0','content'=>'添加失败'];
    		}
		}

		if ($arr['status'] == 0) {
            return $this->error($arr['content'],url('admin/Roles/addRole'));
        } else {
            return $this->success($arr['content'], url('admin/Roles/roleList'));
        }
    }

    // 根据id进行删除
    public function delRole($id)
    {
        $result = Db::name('role')->delete($id);
         if ($result > 0) {
            Db::name('role_node')->where('rid',$id)->delete($id);
            Db::name('admin_role')->where('rid',$id)->delete($id);
            $info['status'] = true;
            $info['id'] = $id;
            $info['msg'] = 'ID为: ' . $id . '的角色删除成功!';
        } else {
            $info['status'] = false;
            $info['id'] = $id;
            $info['msg'] = 'ID为: ' . $id . '的角色删除失败!';
        }

        return json($info);
    }

    //禁用启用切换

    public function changeStatus1($id)
    {
        Role::where('role_id', $id)
                ->update(['role_status' => '2']);
        return $id;
    }

     public function changeStatus2($id)
    {
        Role::where('role_id', $id)
                ->update(['role_status' => '1']);
        return $id;
    }

    public function showEdit($id)
    {
        $arr = Db::name('role_node')->field('nid')->where('rid',$id)->select();
        if(!empty($arr)){
            foreach($arr as $v){
                $newarr[] =  $v['nid'];
            }

        }else{
            $newarr = ['hello'];
        }
        
        $roleall = Role::get($id);
        $nodeall = Node::all();
        $this->assign('rolelist',$roleall);
        $this->assign('nodelist',$nodeall);
        $this->assign('rnarr',$newarr);
        return $this->fetch('role/role-edit');
    }
    public function roleEdit($id)
    {
        $i=0;
        $data = input('post.');
        $ids = $data['id'];
        foreach($ids as $v){
            $idsupdate[$i]['rid'] = $id;
            $idsupdate[$i]['nid'] = $v;
            $i++;
        }

        $roledata['role_name'] = $data['role_name'];
        $roledata['role_power'] = $data['role_power'];
        Db::startTrans();
        try{
            Db::name('role')->where('role_id',$id)->update($roledata);
            Db::name('role_node')->where('rid',$id)->delete();
            DB::name('role_node')->insertAll($idsupdate);
            // 提交事务
            Db::commit();    
            $error = ['status'=>1,'message'=>'修改成功'];
        } catch (\Exception $e) {
            // 回滚事务
            $error = ['status'=>0,'message'=>'修改失败'];
            Db::rollback();
        }

        if ($error['status'] == 0) {
            return $this->error($error['message'],url('admin/Roles/roleEdit'));
        } else {
            return $this->success($error['message'], url('admin/Roles/roleList'));
        }
    }
}
